import 'dart:async';
import 'package:flutter/material.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';

class ResendCodeButton extends StatefulWidget {
  final VoidCallback onResend;

  const ResendCodeButton({super.key, required this.onResend});

  @override
  State<ResendCodeButton> createState() => _ResendCodeButtonState();
}

class _ResendCodeButtonState extends State<ResendCodeButton> {
  int _secondsRemaining = 0;
  Timer? _timer;

  @override
  void initState() {
    super.initState();
    _startCountdown();
  }

  void _resendCode() {
    _startCountdown();

    widget.onResend();
  }

  void _startCountdown() {
    setState(() {
      _secondsRemaining = 60;
    });

    _timer?.cancel();
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_secondsRemaining == 1) {
        timer.cancel();
      }
      setState(() {
        _secondsRemaining--;
      });
    });
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return TextButton(
      onPressed: _secondsRemaining == 0 ? _resendCode : null,
      child: Text(
        _secondsRemaining == 0 ? '重新发送' : '重新发送($_secondsRemaining)秒',
        style: _secondsRemaining > 0
            ? context.textTheme.bodyMedium?.copyWith(
                color: context.customColorThemeNonNull.textColor3,
              )
            : context.textTheme.bodyMedium?.copyWith(
                color: context.colorScheme.primary,
              ),
      ),
    );
  }
}
